package public

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"
	"server/vars"

	"github.com/zeromicro/go-zero/core/logx"
)

type MpLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMpLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MpLoginLogic {
	return &MpLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MpLoginLogic) MpLogin(req *types.LoginReq) (resp *types.TokenResp, err error) {
	// var store = base64Captcha.DefaultMemStore
	// if !store.Verify(req.CaptchaKey, req.CaptchaCode, true) {
	// 	return nil, errors.New("验证码错误")
	// }
	user := &models.Admin{
		Username: req.Username,
	}
	if !utils.GetData(user) {
		return nil, errors.New("用户名或密码错误")
	}
	// if user.Password != utils.MD5(req.Password+user.Salt) {
	if user.Password != utils.MD5(req.Password) {
		return nil, errors.New("用户名或密码错误")
	}

	jwtUser := utils.JwtAdmin{
		Id:       user.ID,
		Username: user.Username,
		RoleId:   user.RoleId,
	}
	token, _ := utils.GetAdminJwtToken(l.svcCtx.Config.Auth.AccessSecret, jwtUser)
	resp = &types.TokenResp{
		UserId:   user.ID,
		Username: user.Username,
		Token:    token,
	}

	// userKey := vars.AdminIdPrefix + utils.UintToString(user.ID)
	// //通过userId找到token,删除token
	// value := utils.GetString(userKey)
	// if value != "" {
	// 	utils.DelCache(vars.AdminTokenPrefix + value)
	// }
	// utils.DelCache(userKey)

	//把token存入redis
	utils.SetStringEx(vars.AdminTokenPrefix+token, utils.StructToJson(jwtUser))
	utils.SetStringEx(vars.AdminIdPrefix+utils.Int64ToString(int64(jwtUser.Id)), token)

	return resp, nil
}
